package com.weilive.core.protocol.json;

import com.weilive.core.protocol.PacketError;

public class JsonResponse {
	private final JsonPacket packet = new JsonPacket();
	
	public static JsonResponse create(Object data) {
		return new JsonResponse(null, data);
	}
	
	public static JsonResponse create(Integer codec,Object data) {
		return new JsonResponse(codec, data);
	}
	
	public static JsonResponse create(PacketError error, Class<?> requestType) {
		return new JsonResponse(error, requestType);
	}
	
	private JsonResponse(Integer codec, Object data) {
		packet.codec = codec;
		packet.type = data.getClass().getSimpleName();
		packet.data = data;
		bindRequest(JsonRequestLocal.getRequest());
	}
	
	private JsonResponse(PacketError error, Class<?> requestType) {
		packet.type = requestType.getSimpleName();
		packet.error = error;
		bindRequest(JsonRequestLocal.getRequest());
	}
	
	public void setError(PacketError error) {
		packet.error = error;
	}
	
	public void cleanError() {
		packet.error = null;
	}
	
	public Integer getId() {
		return packet.id;
	}
	
	public Integer getCodec() {
		return packet.codec;
	}
	
	public void setCodec(Integer codec) {
		packet.codec = codec;
	}
	
	public String getType() {
		return packet.type;
	}
	
	public Object getData() {
		return packet.data;
	}
	
	public PacketError getError() {
		return packet.error;
	}
	
	private void bindRequest(JsonRequest request) {
		if(request != null){
			packet.id = request.getId();
			packet.codec = request.getCodec();
		}
	}
	
	public String encode() throws Exception {
		return packet.encode();
	}
	
	@Override
	public String toString() {
		return packet.toString();
	}
}
